﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace loveMotorcade.web.Areas.manage.Controllers
{
    using Models;
    using Classes;
    public class userController : Controller
    {

        //
        // GET: /manage/user/
        ModelContainer db = new ModelContainer();
        public ActionResult Index()
        {
            
            ViewData.Model = db.user;
            return View();
        }
        public ActionResult Edit(int id = 0)
        {

            user u;
            u = db.user.Where(d => d.ID == id).FirstOrDefault() ?? new user();
            ViewData.Model = u;

            return View();
        }


        //
        // POST: /manage/user/Edit/5

        [HttpPost]
        public ActionResult Edit(int id=0, FormCollection collection= null)
        {
            if (id == 0)
            {
                user cc = new user();

                TryUpdateModel<user>(cc);
                cc.psw = cc.psw.MD5();
                cc.createDate = DateTime.Now;
                cc.editDate = DateTime.Now;
                try
                {
                    // TODO: Add insert logic here


                    db.AddTouser(cc);
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                catch (Exception e)
                {
                    ViewData.Model = cc;
                    return View();
                }
            }
            else
            {
                user cc = db.user.Where(d => d.ID == id).FirstOrDefault();
                if (cc != null)
                {
                    TryUpdateModel<user>(cc);
                    cc.psw = cc.psw.MD5();
                    try
                    {

                        db.SaveChanges();

                        return RedirectToAction("Index");
                    }
                    catch(Exception e)
                    {
                        ViewData.Model = cc;
                        return View();
                    }
                }
                return View();
            }
        }


        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
